<template>
  <div class="app-container">
    <el-card shadow="never" class="filter-container">
      <div class="header">
        <div class="title">
          <el-button type="primary" link @click="backToDevice">
            <el-icon><Back /></el-icon>
          </el-button>
          <span>{{ deviceName }} - 设备数据</span>
        </div>
        <div class="filter">
          <el-form :inline="true" :model="queryParams">
            <el-form-item label="数据类型">
              <el-select v-model="queryParams.data_type" placeholder="请选择数据类型" clearable>
                <el-option label="温度" value="temperature" />
                <el-option label="湿度" value="humidity" />
                <el-option label="电压" value="voltage" />
                <el-option label="电流" value="current" />
                <el-option label="功率" value="power" />
                <el-option label="状态" value="status" />
              </el-select>
            </el-form-item>
            <el-form-item label="告警状态">
              <el-select v-model="queryParams.is_alarm" placeholder="请选择告警状态" clearable>
                <el-option label="正常" :value="0" />
                <el-option label="告警" :value="1" />
              </el-select>
            </el-form-item>
            <el-form-item label="时间范围">
              <el-date-picker
                v-model="dateRange"
                type="datetimerange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                format="YYYY-MM-DD HH:mm:ss"
                value-format="YYYY-MM-DD HH:mm:ss"
                :shortcuts="dateShortcuts"
              />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="handleQuery">查询</el-button>
              <el-button @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </div>
      </div>
    </el-card>

    <el-row :gutter="20" style="margin-top: 20px">
      <el-col :span="24">
        <el-card shadow="never" class="data-chart-container">
          <template #header>
            <div class="chart-header">
              <span>数据趋势</span>
              <div>
                <el-radio-group v-model="chartType" size="small" @change="refreshChart">
                  <el-radio-button label="line">折线图</el-radio-button>
                  <el-radio-button label="bar">柱状图</el-radio-button>
                </el-radio-group>
              </div>
            </div>
          </template>
          <div v-if="!chartData.length" class="empty-chart">
            <el-empty description="暂无数据" />
          </div>
          <div v-else ref="chartRef" class="chart"></div>
        </el-card>
      </el-col>
    </el-row>

    <el-card shadow="never" class="data-table-container" style="margin-top: 20px">
      <template #header>
        <div class="card-header">
          <span>历史数据</span>
        </div>
      </template>

      <el-table v-loading="loading" :data="dataList" border stripe style="width: 100%">
        <el-table-column type="index" width="50" label="#" align="center" />
        <el-table-column prop="data_type" label="数据类型" min-width="100">
          <template #default="scope">
            {{ formatDataType(row.data_type) }}
          </template>
        </el-table-column>
        <el-table-column prop="data_value" label="数据值" min-width="120" />
        <el-table-column prop="unit" label="单位" width="80" />
        <el-table-column label="告警状态" width="100" align="center">
          <template #default="scope">
            <el-tag :type="row.is_alarm ? 'danger' : 'success'">
              {{ row.is_alarm ? '告警' : '正常' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="告警类型" width="100" align="center">
          <template #default="scope">
            <el-tag v-if="row.is_alarm" :type="alarmType(row.alarm_type)">
              {{ alarmTypeText(row.alarm_type) }}
            </el-tag>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column prop="alarm_threshold" label="告警阈值" min-width="100">
          <template #default="scope">
            {{ row.alarm_threshold || '-' }}
          </template>
        </el-table-column>
        <el-table-column prop="data_time" label="数据时间" min-width="180" />
      </el-table>
      
      <el-pagination
        v-if="total > 0"
        :total="total"
        v-model:currentPage="queryParams.page"
        v-model:page-size="queryParams.pageSize"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        layout="total, sizes, prev, pager, next, jumper"
        :page-sizes="[10, 20, 50, 100]"
        style="margin-top: 20px; justify-content: flex-end"
      />
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { getDeviceData } from '@/api/device'
import { ElMessage } from 'element-plus'
import { Back } from '@element-plus/icons-vue'
import * as echarts from 'echarts'

const route = useRoute()
const router = useRouter()
const deviceId = computed(() => route.params.id)
const deviceName = computed(() => route.query.name || '未知设备')

// 查询参数
const queryParams = reactive({
  page: 1,
  pageSize: 10,
  data_type: '',
  is_alarm: '',
  start_time: '',
  end_time: ''
})

// 日期范围
const dateRange = ref([])
const dateShortcuts = [
  {
    text: '最近一小时',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000)
      return [start, end]
    }
  },
  {
    text: '今天',
    value: () => {
      const end = new Date()
      const start = new Date(new Date().toDateString())
      return [start, end]
    }
  },
  {
    text: '最近24小时',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24)
      return [start, end]
    }
  },
  {
    text: '最近7天',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
      return [start, end]
    }
  }
]

// 数据列表
const dataList = ref([])
const loading = ref(false)
const total = ref(0)

// 图表相关
const chartRef = ref(null)
const chartType = ref('line')
const chartData = ref([])
let chart = null

// 监听日期变化
watch(dateRange, (val) => {
  if (val) {
    queryParams.start_time = val[0]
    queryParams.end_time = val[1]
  } else {
    queryParams.start_time = ''
    queryParams.end_time = ''
  }
})

// 获取设备数据
const getList = async () => {
  if (!deviceId.value) return
  
  loading.value = true
  try {
    const res = await getDeviceData(deviceId.value, queryParams)
    dataList.value = res.data.data || []
    total.value = res.data.total || 0
    prepareChartData()
  } catch (error) {
    console.error('获取设备数据失败', error)
    dataList.value = []
    total.value = 0
    chartData.value = []
  } finally {
    loading.value = false
  }
}

// 准备图表数据
const prepareChartData = () => {
  if (!dataList.value.length) {
    chartData.value = []
    return
  }

  // 处理图表数据，按数据类型分组
  const dataMap = {}
  const times = []
  const timeSet = new Set()

  dataList.value.forEach(item => {
    const type = item.data_type
    if (!dataMap[type]) {
      dataMap[type] = []
    }
    dataMap[type].push({
      value: parseFloat(item.data_value),
      time: item.data_time
    })
    timeSet.add(item.data_time)
  })

  Array.from(timeSet).sort().forEach(time => times.push(time))
  
  const series = []
  for (const type in dataMap) {
    const data = []
    times.forEach(time => {
      const found = dataMap[type].find(item => item.time === time)
      data.push(found ? found.value : null)
    })
    
    series.push({
      name: formatDataType(type),
      type: chartType.value,
      data
    })
  }
  
  chartData.value = {
    times,
    series
  }
  
  refreshChart()
}

// 刷新图表
const refreshChart = () => {
  if (!chartData.value || !chartData.value.times) return
  
  if (!chart && chartRef.value) {
    chart = echarts.init(chartRef.value)
  }
  
  if (chart) {
    const option = {
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'cross'
        }
      },
      legend: {
        data: chartData.value.series.map(s => s.name)
      },
      grid: {
        left: '3%',
        right: '4%',
        bottom: '3%',
        containLabel: true
      },
      xAxis: {
        type: 'category',
        boundaryGap: chartType.value === 'bar',
        data: chartData.value.times
      },
      yAxis: {
        type: 'value'
      },
      series: chartData.value.series.map(s => ({
        ...s,
        type: chartType.value,
        smooth: chartType.value === 'line'
      }))
    }
    
    chart.setOption(option)
  }
}

// 格式化数据类型
const formatDataType = (type) => {
  const typeMap = {
    'temperature': '温度',
    'humidity': '湿度',
    'voltage': '电压',
    'current': '电流',
    'power': '功率',
    'status': '状态'
  }
  return typeMap[type] || type
}

// 告警类型
const alarmTypeText = (type) => {
  const typeMap = {
    0: '正常',
    1: '警告',
    2: '一般',
    3: '严重',
    4: '紧急'
  }
  return typeMap[type] || '未知'
}

const alarmType = (type) => {
  const typeMap = {
    0: '',
    1: 'warning',
    2: 'info',
    3: 'danger',
    4: 'danger'
  }
  return typeMap[type] || ''
}

// 查询操作
const handleQuery = () => {
  queryParams.page = 1
  getList()
}

// 重置查询
const resetQuery = () => {
  dateRange.value = []
  queryParams.data_type = ''
  queryParams.is_alarm = ''
  queryParams.start_time = ''
  queryParams.end_time = ''
  handleQuery()
}

// 分页处理
const handleSizeChange = (size) => {
  queryParams.pageSize = size
  getList()
}

const handleCurrentChange = (page) => {
  queryParams.page = page
  getList()
}

// 返回设备列表
const backToDevice = () => {
  router.push({ path: '/device' })
}

// 窗口大小变化时重绘图表
const handleResize = () => {
  if (chart) {
    chart.resize()
  }
}

onMounted(() => {
  window.addEventListener('resize', handleResize)
  getList()
})

// 组件卸载前移除事件监听
const onBeforeUnmount = () => {
  window.removeEventListener('resize', handleResize)
  if (chart) {
    chart.dispose()
    chart = null
  }
}
</script>

<style lang="scss" scoped>
.app-container {
  padding: 20px;
}

.filter-container {
  .header {
    display: flex;
    flex-direction: column;
    
    .title {
      display: flex;
      align-items: center;
      font-size: 18px;
      font-weight: bold;
      margin-bottom: 15px;
    }
    
    .filter {
      margin-top: 10px;
    }
  }
}

.card-header, .chart-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.data-chart-container {
  height: 400px;
  
  .chart {
    height: 340px;
  }
  
  .empty-chart {
    height: 340px;
    display: flex;
    align-items: center;
    justify-content: center;
  }
}

:deep(.el-card__header) {
  padding: 10px 20px;
}
</style> 